package service

import (
	"fmt"

	"zhonghui/console/warehouse/cfgx"
	"zhonghui/console/warehouse/logx"

	"github.com/ddliu/go-httpclient"
	jsoniter "github.com/json-iterator/go"
)

type AuthCorpInfo struct {
	Corpid            string `json:"corpid"`
	CorpName          string `json:"corp_name"`
	CorpType          string `json:"corp_type"`
	CorpRoundLogoURL  string `json:"corp_round_logo_url"`
	CorpSquareLogoURL string `json:"corp_square_logo_url"`
	CorpScale         string `json:"corp_scale"`
	CorpIndustry      string `json:"corp_industry"`
	CorpSubIndustry   string `json:"corp_sub_industry"`
	CorpFullName      string `json:"corp_full_name"`
	CorpUserMax       int64  `json:"corp_user_max"`
	CorpWxqrcode      string `json:"corp_wxqrcode"`
	Location          string `json:"location"`
	SubjectType       int64  `json:"subject_type"`
	VerifiedEndTime   int64  `json:"verified_end_time"`
}

type PermanentCodeResponse struct {
	AccessToken   string       `json:"access_token"`
	ExpiresIn     int64        `json:"expires_in"`
	PermanentCode string       `json:"permanent_code"`
	AuthCorpInfo  AuthCorpInfo `json:"auth_corp_info"`

	AuthInfo     string // 这两个字段太复杂,直接记录原始值
	AuthUserInfo string
}

func GetPermanentCode(authCode, suiteAccessToken string) (*PermanentCodeResponse, error) {
	data := PermanentCodeResponse{}

	body := struct {
		AuthCode string `json:"auth_code"`
	}{
		authCode,
	}
	host := cfgx.Cfg().GetString("wx.host")
	url := fmt.Sprintf("%s/cgi-bin/service/get_permanent_code?suite_access_token=%s", host, suiteAccessToken)

	jsonBody, err := jsoniter.MarshalToString(body)
	if err != nil {
		return nil, err
	}

	res, err := httpclient.PostJson(url, jsonBody)
	if err != nil {
		return nil, err
	}

	logx.Zap().Infow("GetPermanentCode-new", "err", err, "jsonBody", jsonBody, "baby", res)

	ret, err := res.ToString()
	if err != nil {
		return nil, err
	}

	logx.Zap().Infow("GetPermanentCode-after", "err", err, "ret", ret)

	if err := jsoniter.Unmarshal([]byte(ret), &data); err != nil {
		logx.Zap().Errorw("解析PermanentCode失败", "err", err)
		return &data, err
	}

	data.AuthInfo = jsoniter.Get([]byte(ret), "auth_info").ToString()
	data.AuthUserInfo = jsoniter.Get([]byte(ret), "auth_user_info").ToString()
	return &data, nil
}
